﻿CREATE PROCEDURE [dbo].[Text_Save]
	@userId UNIQUEIDENTIFIER
	,	@textId BIGINT
	, @hashTag NVARCHAR(128)
	, @tag NVARCHAR(32)
	, @value NVARCHAR(MAX)
AS
BEGIN
	DECLARE @chapterId UNIQUEIDENTIFIER

	SET @hashTag = LOWER(@hashTag)

	SELECT @chapterId = t.[ChapterId]
	FROM [dbo].[text_Text] AS t
	INNER JOIN [dbo].[text_Chapter] AS c ON t.[ChapterId] = c.[ChapterId]
	WHERE t.[TextId] = @textId AND c.[HashTag] = @hashTag

	IF @chapterId IS NULL OR [dbo].[IsViewUnpublished](@userId) <> 1
		RETURN

	BEGIN TRY
		BEGIN TRANSACTION
			UPDATE [dbo].[text_Text]
			SET	[Tag] = @tag
					,	[Value] = @value
			 WHERE [ChapterId] = @chapterId AND [TextId] = @textId

			UPDATE [dbo].[text_Chapter]
			SET [UpdateDate] = GETUTCDATE()
			WHERE [ChapterId] = @chapterId

	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT	@ErrorMessage = ERROR_MESSAGE(),
						@ErrorSeverity = ERROR_SEVERITY(),
						@ErrorState = ERROR_STATE();

		RAISERROR (
								@ErrorMessage, -- Message text.
								@ErrorSeverity, -- Severity.
								@ErrorState -- State.
							);

	END CATCH

END